const path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin"); // 每次打包时清除旧的文件
const HtmlWebpackPlugin = require("html-webpack-plugin"); //创建html文件
const buildConfig = require("./webpack.build");
const TerserWebpackPlugin = require("terser-webpack-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");

const webpack = require("webpack");
const getEntry = () => {
  //遍历获取文件入口  可配置为多页面
  const rEntry = {};
  buildConfig.entries.forEach((item) => {
    rEntry[item.key] = item.entry;
  });

  return rEntry;
};
const getHtmlPlugin = () => {
  return buildConfig.entries.map((item) => {
    return new HtmlWebpackPlugin({
      title: item.title,
      filename: item.key + ".html",
      template: "./src/index.ejs",
      favicon: "./favicon.ico", // 配置favicon
      chunks: [item.key, "common"],
      minify: {
        removeAttributeQuotes: true, //删除引号
        removeComments: true, //移除html中的注释
        collapseWhitespace: true, //移除空白符和换行符
        minifyCss: true, //压缩内联css
      },
    });
  });
};
module.exports = {
  mode: process.env.NODE_ENV_MODE,
  entry: getEntry(), //文件入口
  output: {
    // 文件出口
    path: path.resolve(__dirname, "dist/"),
    filename: "[name]-[contenthash:6].js", // 文件名
    // sourceMapFilename: "../maps/[name].map", // sourceMap文件名
    // publicPath: "./",
  },
  stats: {
    //打包时输出的打包文件
    colors: true, //true时不同的文件颜色不同
    modules: false,
    children: false,
    excludeAssets: (asset) => {
      //那些文件需要输出打印于控制台
      return (
        asset.lastIndexOf(".js") !== asset.length - 3 &&
        asset.lastIndexOf(".css") !== asset.length - 4 &&
        asset.lastIndexOf(".html") !== asset.length - 5
      );
    },
  },
  resolve: {
    modules: [path.resolve(__dirname, "node_modules")], // 设置第三方依赖地址   以节约时间
    extensions: [".ts", ".tsx", ".js", ".json", ".jsx"], //设置导入时可不用写后缀的文件类型（不建议多写，会影响打包速度）
    mainFields: ["browser", "module", "main"],
    alias: {
      //快捷路径
      // "react": path.resolve(__dirname, "./node_modules/react/umd/react.production.min.js"),
      // "react-dom": path.resolve(__dirname, "./node_modules/react-dom/umd/react-dom.production.min.js"),
      "@": path.resolve(__dirname, "./src"),
    },
  },
  optimization: {
    splitChunks: {
      name: "common",
      chunks: "initial",
      cacheGroups: {
        common: {
          name: "common",
          chunks: "initial",
          priority: 2,
          minChunks: 2,
        },
      },
    },
    // minimize: true,
    minimizer: [
      new TerserWebpackPlugin(), //在minimize开启时  需要手动开启js压缩   在没有开启时webpack会内置将js打包
      new CssMinimizerPlugin({
        exclude: /node-modules/,
        parallel: 4, //开启多线程
        minimizerOptions: {
          preset: [
            "default",
            {
              discardComments: { removeAll: true },
            },
          ],
        },
      }), //webpack5中使用此插件  并非OptimizeCssAssetsPlugin
    ],
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx|ts|tsx)$/,
        exclude: /node-modules/,
        include: path.resolve(__dirname, "./src"),
        loader: "babel-loader",
      },
      {
        test: /\.(png|jpg|jpeg|svg|gif|woff|ttf|eot)$/,
        include: path.resolve(__dirname, "./src"),
        use: {
          loader: "file-loader",
          options: {
            limit: 10000,
            name: "assets/img/[name].[ext]",
          },
        },
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        include: path.resolve(__dirname, "./src"),
        use: {
          loader: "file-loader",
          options: {
            limit: 10000,
            name: "assets/Particle/[name].[ext]",
          },
        },
      },
    ],
  },
  plugins: [
    new CleanWebpackPlugin(),
    new webpack.DefinePlugin({
      API: "'" + "webpack环境中定义的常量API" + "'",
      NODE: "'" + "webpack环境中定义的常量NODE" + "'",
    }),
  ].concat(getHtmlPlugin()),
};
